<script setup>
import {PerfectScrollbar} from 'vue3-perfect-scrollbar'
import {VForm} from 'vuetify/components/VForm'
import {defineEmits, ref} from "vue";
import {useApi} from "@/composables/useApi.js";
import showTost from "@/components/toast/index.js";

const props = defineProps({
  isDrawerOpen: {
    type: Boolean,
    required: true,
  },
  detailData: {
    type: Object,
    required: true
  },
  title: {
    type: String,
    default: '详情'
  },

  studentList: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:isDrawerOpen', 'onHandleEdit', 'onHandleDelete'])

const handleDrawerModelValueUpdate = val => {
  emit('update:isDrawerOpen', val)
}

const refVForm = ref()
const resetForm = () => {


  emit('update:isDrawerOpen', false)
}

const closeNavigationDrawer = () => {
  emit('update:isDrawerOpen', false)
  nextTick(() => {
    refVForm.value?.reset()
    refVForm.value?.resetValidation()
  })
}
const form = ref({})
const assignmentData = () => {
  console.log(props.detailData)
  form.value = JSON.parse(JSON.stringify(props.detailData))
}

import {storeToRefs} from "pinia"
import {useAppStore} from "../../../store/app"
import {standardAddModify} from "@/api/standard.js";

const appStore = useAppStore()

const {nationArr, sexArr} = storeToRefs(appStore)
watch(() => props.isDrawerOpen, () => {
  assignmentData()
})
const isEdit = ref(false)
let sexList = ref(['男', '女'])

const onHandleEditData = async () => {
  if (isEdit.value === true) {
    standardAddModify({...form.value,totalScore:totalScore.value}).then(res=>{
      emit('onHandleEdit')
      showTost("修改成功", {duration: 3000, type: "success"})
      emit('update:isDrawerOpen', false)
      isEdit.value = false
    })

  } else {
    isEdit.value = true
  }
}
const updatePassword = async () => {
  const {data} = await useApi('/teacher/Api.Teacher/resetPwd').post({
    teacher_id: props.detailData.teacher_id,
    password: '000000'
  })
  if (data.value.status == 200) {
    showTost("重置密码成功", {duration: 3000, type: "success"})

    emit('onHandleEdit')
  }
}
const onDelete = () => {
  emit('onHandleDelete', form.value)
}
const required = (value, name) => !!value || `${name}为必填字段`;
const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== 'Backspace' && event.key !== 'Tab') {
    event.preventDefault();
  }
}
const filterInput =(key) => {
  // 仅保留数字
  form.value[key] = form.value[key].replace(/\D/g, '');
}
let totalScore = computed(()=>{
  return Number(form.value.languageScore)    +  Number(form.value.mathsScore) + Number(form.value.englishScore)
})
watch(()=>form.student_id,val=>{
  console.log(val)
  if(val==null){
    form.classTitle = ''
    form.gradeTitle = ''
    return
  }
  let item = studentList.value.find(item=>item.student_id == val)
  form.classTitle = item.classTitle
  form.gradeTitle = item.gradeTitle
})
</script>

<template>
  <VNavigationDrawer
    :model-value="props.isDrawerOpen"
    temporary
    location="end"
    width="370"
    @update:model-value="handleDrawerModelValueUpdate"
  >
    <!-- 👉 Header -->
    <AppDrawerHeaderSection
      :title="title"
      @cancel="closeNavigationDrawer"
    />
    <VDivider/>

    <VCard flat>
      <PerfectScrollbar
        :options="{ wheelPropagation: false }"
        class="h-100"
      >
        <VCardText style="block-size: calc(100dvh - 5rem);display: flex;flex-direction: column;">
          <VForm
            :disabled="!isEdit"
            ref="refVForm"
            @submit.prevent=""
          >
            <VRow>
              <VCol cols="12">
                <div class="text-body-1 font-weight-medium text-high-emphasis">
                  基本信息
                </div>
              </VCol>
              <VCol cols="6">
                <VSelect
                  v-model="form.student_id"
                  :items="props.studentList"
                  item-title="real_name"
                  item-value="student_id"
                  :rules="[(val)=>required(val,'学生姓名')]"
                  class="input-width-height"
                >
                  <template v-slot:label>
                    <span>学生姓名</span>
                    <span style="color: red;margin-left: 4px;">*</span>
                  </template>
                </VSelect>

              </VCol>
              <VCol cols="6">
                <VTextField
                  disabled
                  v-model="form.student_id"
                  label="学生ID"
                  :rules="[(val)=>required(val,'学生ID')]"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="form.gradeTitle"
                  disabled
                  label="所属年级"
                >
                </VTextField>
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="form.classTitle"
                  disabled
                  label="所属班级"
                >
                </VTextField>
              </VCol>
              <VCol cols="6">
                <AppDateTimePicker
                  class="input-width-height"
                  v-model="form.examinationTime"
                  label="考试时间"
                  placeholder="请选择考试时间"
                  :rules="[(val)=>required(val,'考试时间')]"
                >
                  <template v-slot:label>
                    <span>考试时间</span>
                    <span  style="color: red;margin-left: 4px;">*</span>
                  </template>
                </AppDateTimePicker>

              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="form.languageScore"
                  @keypress="onlyAllowNumbers"
                  @input="()=>filterInput('languageScore')"
                  label="语文分数"
                  :rules="[(val)=>required(val,'语文分数')]"
                  placeholder="请输入语文分数"
                >
                  <template v-slot:label>
                    <span>语文分数</span>
                    <span  style="color: red;margin-left: 4px;">*</span>
                  </template>
                </VTextField>
              </VCol>

              <VCol cols="6">
                <VTextField
                  v-model="form.mathsScore"
                  @keypress="onlyAllowNumbers"
                  @input="()=>filterInput('mathsScore')"
                  label="数学分数"
                  :rules="[(val)=>required(val,'数学分数')]"
                  placeholder="请输入数学分数"
                >
                  <template v-slot:label>
                    <span>数学分数</span>
                    <span  style="color: red;margin-left: 4px;">*</span>
                  </template>
                </VTextField>
              </VCol>

              <VCol cols="6">
                <VTextField
                  v-model="form.englishScore"
                  label="英语分数"
                  @keypress="onlyAllowNumbers"
                  @input="()=>filterInput('englishScore')"
                  :rules="[(val)=>required(val,'英语分数')]"
                  placeholder="请输入英语分数"
                >
                  <template v-slot:label>
                    <span>英语分数</span>
                    <span  style="color: red;margin-left: 4px;">*</span>
                  </template>
                </VTextField>
              </VCol>
              <VCol cols="6">
                <VTextField
                  disabled
                  v-model="totalScore"
                  label="总分"
                  :rules="[(val)=>required(val,'总分')]"
                  placeholder="请输入总分"
                />
              </VCol>


            </VRow>
          </VForm>
            <div class="d-flex justify-end" style="height:60px;margin-top: auto">

              <VBtn
                color="primary"
                class="me-4"
                @click="onHandleEditData"
              >
                {{ isEdit == true ? '保存' : '编辑' }}
              </VBtn>
              <VBtn
                color="error"
                variant="outlined"
                @click="onDelete"
              >
                删除
              </VBtn>
            </div>
        </VCardText>
      </PerfectScrollbar>
    </VCard>
  </VNavigationDrawer>
</template>

<style lang="scss">
.v-navigation-drawer__content {
  overflow-y: hidden !important;
}
</style>
